package cn.zhqr.lib.utils;

import cn.zhqr.common.util.str.StringUtils;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.regex.Pattern;

public class UrlKit {
    private static final Logger logger = Logger.getLogger(UrlKit.class);
    private static final String UTF8 = "utf-8";
    private static final String GBK = "gbk";

    public static String getHost(String url){
//        if(StrKit.notBlank(url) && url.contains(":")){
//            url = url.trim().substring(0,url.indexOf(":"));
//        }
//        return url;
        Pattern pattern = Pattern.compile("^[a-zA-Z]{0,10}://");
        if(!pattern.matcher(url).find()){
            url = "http://"+url;
        }
        URI uri = URI.create(url);
        return uri.getHost();
    }

    public static boolean isURL(String url){
        if(StringUtils.isBlank(url)){
            return false;
        }
        //转换为小写
        url = url.toLowerCase().trim();

        String regex = "^((https|http)?://)?"  //https、http
                + "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 例如：199.194.52.184
                + "|" // 允许IP和DOMAIN（域名）
                + "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.
                + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名
                + "[a-z]{2,6})" // first level domain- .com or .museum
                + "(:[0-9]{1,5})?" // 端口号最大为65535,5位数
                + "((/?)|" // a slash isn't required if there is no file name
                + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        return url.matches(regex);
    }

    public static boolean testConnect(String webUrl){
        if(StringUtils.isBlank(webUrl)){
            return false;
        }
        webUrl = webUrl.trim();
        if(!webUrl.startsWith("http")){
            webUrl = "https://"+webUrl;
        }
        try {
            URL url = new URL(webUrl);
            URLConnection rulConnection   = url.openConnection();
            HttpURLConnection httpUrlConnection  =  (HttpURLConnection) rulConnection;
            httpUrlConnection.setConnectTimeout(30000);
            httpUrlConnection.setReadTimeout(30000);
            httpUrlConnection.connect();
            String code = new Integer(httpUrlConnection.getResponseCode()).toString();
            String message = httpUrlConnection.getResponseMessage();
            logger.debug("test connect "+webUrl+"  response code ="+ code+" message"+message);
            return code.startsWith("2") || code.startsWith("3");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String utf8Encode(String str){
        try {
            return URLEncoder.encode(str,UTF8);
        } catch (UnsupportedEncodingException e) {
            //此处明确不会抛出此异常，所以可以不处理
        }
        return "";
    }

    public static String gbkEncode(String str){
        try {
            return URLEncoder.encode(str,GBK);
        } catch (UnsupportedEncodingException e) {
            //此处明确不会抛出此异常，所以可以不处理
        }
        return "";
    }



    public static void main(String[] args) {
    }
}
